import getopt
import os
import sys

from Crypto.Cipher import AES
from lib.mysign import my_sign


def show_help():
    print("-h                       查看帮助")
    print("-s <path>                bin文件路径         例: E:\\abc.bin")
    print("-o <path>                dfu文件输出路径     例: D:\\")
    print("-n <path>                取反间隔            例: 4")
    print("完整例子: xxx.exe -s E:\\abc.bin -o D:\\ -n 4")

if __name__ == "__main__":
    # print(sys.argv)
    py_path = os.path.dirname(sys.argv[0])

    mysign = my_sign(py_path)

    sour_path = None
    out_path = None
    negation_interval = 4

    try:
        opts, args = getopt.getopt(sys.argv[1:], '-h-s:-o:-n:',
                                   ['help', 'source=', 'out=', 'nega='])
    except Exception:
        print("参数错误!")
        sys.exit()

    for opt_name, opt_value in opts:
        if opt_name in ('-h', '--help'):
            show_help()
            sys.exit()
        elif(opt_name in ('-s', '--source')):
            sour_path = opt_value
        elif(opt_name in ('-o', '--out')):
            out_path = opt_value
        elif(opt_name in ('-n', '--nega')):
            negation_interval = int(opt_value)

    # print(sour_path)
    if sour_path is not None:
        data = mysign.get_data(sour_path)
    else:
        sys.exit()
    # print("sour_path:", sour_path)

    if len(data) != 0:
        size = os.path.getsize(sour_path)
        # 得到输出路径
        out_path = mysign.get_out_path(sour_path, out_path)
        print("out path:", out_path)
        # 计算crc16
        crc16 = mysign.get_crc16(data)
        # 得到头信息
        head_info = mysign.get_head_info(crc16, size)
        # 加密
        data_v = bytearray(data)
        if(negation_interval != 0):
            len_i = 0
            while 1:
                len_i += negation_interval
                if(len_i >= size):
                    break
                else:
                    # print(len_i, len(data_v))
                    a = (~(data_v[len_i]) & 0xFF).to_bytes(
                        2, byteorder='big', signed=True)
                    data_v[len_i] = a[1]
        data_t = bytearray(data_v)
        # 写出dfu文件
        with open(out_path, 'wb') as f:
            f.write(head_info + bytes([negation_interval]) + data_t)
            f.close()

    else:
        print("err: Invalid parameter")
